package io.github.uicdb.badskill;

import com.google.common.collect.Maps;
import com.google.gson.JsonElement;
import io.github.uicdb.badskill.codec.JsonFactory;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener;
import net.minecraft.util.profiling.ProfilerFiller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SkillPageManager extends SimpleJsonResourceReloadListener {
    public static final SkillPageManager INSTANCE=new SkillPageManager();
    public final HashMap<ResourceLocation,SkillPage> PAGES=new HashMap<>();
    private final List<SkillPage> PAGES_LIST=new ArrayList<>();

    public List<SkillPage> getPageList() {
        return PAGES_LIST;
    }

    public static final SkillPage EMPTY=new SkillPage.SkillPageBuilder().id(new ResourceLocation(BadSkill.MODID,"empty")).locations(Maps.newConcurrentMap()).build();
    public SkillPage safeGet(int index){
        if(index>=PAGES_LIST.size())
            return EMPTY;
        return PAGES_LIST.get(index);
    }
    public SkillPage safeGet(ResourceLocation id){
        return PAGES.getOrDefault(id,EMPTY);
    }
    public SkillPageManager() {
        super(JsonFactory.create(),"skill_page");
    }

    @Override
    protected void apply(Map<ResourceLocation, JsonElement> elementMap, ResourceManager pResourceManager, ProfilerFiller pProfiler) {
        PAGES.clear();
        PAGES_LIST.clear();
        elementMap.forEach((resourceLocation, element) -> {
            var page = SkillPage.fromJson(element);
            PAGES.put(page.id, page);
            PAGES_LIST.add(page);
        });
    }
}
